<template>
  <div class="app-container">

    <el-card class="box-card">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="150px" v-loading='loading'>

        <el-form-item label="上传图片" prop="bannerImg">
          <el-upload :data="dataUp" :headers="headers" :on-remove="handleRemove" :limit="1" :file-list="fileList" list-type="picture-card" ref="uploadIMG" :action="uploadPath" :auto-upload="false" :on-error="fileError" :on-success="handleAvatarSuccess" :on-change="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="名称：">
          <el-input v-model="ruleForm.gameName" />
        </el-form-item>
        <el-form-item label="开发商：">
          <el-input v-model="ruleForm.developers" />
        </el-form-item>

        <!-- <el-form-item label="版本选择：">
          <el-select v-model="ruleForm.version" placeholder="请选择">
            <el-option v-for="item in versionTypeID" :key="item.id" :label="item.displayName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="特色选择：">
          <el-select v-model="ruleForm.featuresId" placeholder="请选择">
            <el-option v-for="item in featuresId" :key="item.id" :label="item.displayName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="开服时间：">
          <el-col :span="6">
            <el-form-item>
              <el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择开始日期" v-model="startTimeDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1" style="width:10px;">-</el-col>
          <el-col :span="5">
            <el-form-item>
              <el-time-picker placeholder="选择开始时间" format="HH:mm:ss" value-format="HH:mm:ss" v-model="startTimeShijian" style="width: 100%;"></el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="是否有安卓：">
          <el-switch v-model="ruleForm.haveAndroid"></el-switch>
        </el-form-item>
        <el-form-item label="是否有IOS：">
          <el-switch v-model="ruleForm.haveIos"></el-switch>
        </el-form-item>

        <el-form-item label="排名：" prop="sortNum">
          <el-input-number v-model="ruleForm.ranking" :min=0 controls-position="right"></el-input-number>
          <!-- <label style="margin-left: 20px;">数字越小越靠前</label> -->
        </el-form-item>
        <el-form-item label="游戏评分：" prop="sortNum">
          <el-input-number v-model="ruleForm.score" :min=0 controls-position="right"></el-input-number>
          <!-- <label style="margin-left: 20px;">数字越小越靠前</label> -->
        </el-form-item>

        <el-form-item label="总人气：">
          <el-input-number v-model="ruleForm.totalPopularity" :min=0 controls-position="right"></el-input-number>
          <!-- <label style="margin-left: 20px;">数字越小越靠前</label> -->
        </el-form-item>

        <el-form-item label="顶部推荐：">
          <el-switch v-model="ruleForm.isRecommend"></el-switch>
          <span v-if="ruleForm.isRecommend" style="margin-left: 25px;">顶部排序：</span>
          <el-input-number v-if="ruleForm.isRecommend" v-model="ruleForm.recommendSort" :min=0 controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="新游推荐：">
          <el-switch v-model="ruleForm.newTour"></el-switch>
          <span v-if="ruleForm.newTour" style="margin-left: 25px;">新游排序：</span>
          <el-input-number v-if="ruleForm.newTour" v-model="ruleForm.newTourSort" :min=0 controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="新服推荐：">
          <el-switch v-model="ruleForm.newClothes"></el-switch>
        </el-form-item>

        <el-form-item label="状态：">
          <el-radio v-model="ruleForm.status" :label=1>测试</el-radio>
          <el-radio v-model="ruleForm.status" :label=2>已开服</el-radio>
        </el-form-item>

        <el-form-item label="内容简介：">
          <el-input v-model="ruleForm.simpleText" type="textarea" />
        </el-form-item>

        <el-form-item label="内容详细" prop="content">
          <div style="border: 1px solid #ccc; margin-top: 10px;">
            <!-- 工具栏 -->
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
            <!-- 编辑器 -->
            <Editor style="height: 400px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="ruleForm.details" @onChange="onChange" @onCreated="onCreated" />
          </div>

        </el-form-item>

        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button :loading='loading' type="primary" @click="handlePublish">保存</el-button>
        </el-form-item>

      </el-form>
    </el-card>

  </div>
</template>



<script>
import api from '@/api/gameBox'
import { create, displaytypeList } from '@/api/version/goods'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import storage, { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  name: 'cmsCreate',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          uploadImage: {
            server: uploadPath,
            fieldName: 'file',
            headers: {
              'X-Hyxxkj-Admin-Token': getToken()
            },
            meta: {
              dirName: ''
            },
            onSuccess: () => {},
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          },
          uploadVideo: {
            server: uploadPath,
            fieldName: 'file',
            headers: {
              'X-Hyxxkj-Admin-Token': getToken()
            },
            meta: {
              dirName: ''
            },
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          }
        }
      },
      dataUp: { dirName: '' },
      fileList: [],
      uploadPath: uploadPath,
      loading: false,
      versionTypeID: '',
      featuresId: '',
      startTimeDate: '',
      startTimeShijian: '',
      isImgCheak: false,
      ruleForm: {
        bannerImg: '', // banner图
        developers: '', // 开发商
        version: '', // 版本
        featuresId: '', // 特色
        gameName: '', // 游戏名称
        haveAndroid: false, // 是否安卓
        haveIos: false, // 是否ios
        openAreaTime: '', // 开放时间
        isRecommend: false, // 顶部推荐 0不 1是
        newClothes: false, // 新服推荐  0不 1是
        newTour: false, // 新游推荐  0不 1
        newTourSort: 0, // 新由推荐排序
        ranking: 0, // 排名
        recommendSort: 0, // 顶部推荐排序
        score: 0, // 游戏评分
        simpleText: '', // 简介
        status: 1, // 状态  1测试 2已开服
        totalPopularity: 0, // 总人气
        details: '' // 详情
      },
      rules: {
        bannerImg: [{ required: true, message: '请选择图片', trigger: 'blur' }]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {},
  mounted() {
    // displaytypeList({ type: 0 }).then((res) => {
    //   this.versionTypeID = res.data.data.list
    // })
    // displaytypeList({ type: 4 }).then((res) => {
    //   this.featuresId = res.data.data.list
    // })
    this.init()
  },
  methods: {
    init() {
      if (this.$route.query.id == null) {
        return
      }
      const id = this.$route.query.id
      api.read({ id: id }).then((res) => {
        var data = res.data.data.boxgame
        // var s=data.openAreaTime.split(" ")
        this.ruleForm.addTime = data.addTime
        this.ruleForm.bannerImg = data.bannerImg
        this.ruleForm.deleted = data.deleted
        this.ruleForm.details = data.details
        this.ruleForm.developers = data.developers
        this.ruleForm.featuresId = data.featuresId
        this.ruleForm.gameName = data.gameName
        this.ruleForm.haveAndroid = data.haveAndroid
        this.ruleForm.haveIos = data.haveIos
        this.ruleForm.id = data.id
        this.ruleForm.isRecommend = data.isRecommend
        this.ruleForm.newClothes = data.newClothes
        this.ruleForm.newTour = data.newTour
        this.ruleForm.newTourSort = data.newTourSort
        this.ruleForm.openAreaTime = data.openAreaTime
        this.ruleForm.ranking = data.ranking
        this.ruleForm.recommendSort = data.recommendSort
        this.ruleForm.score = data.score
        this.ruleForm.simpleText = data.simpleText
        this.ruleForm.status = data.status
        this.ruleForm.totalPopularity = data.totalPopularity
        this.ruleForm.updateTime = data.updateTime
        this.ruleForm.version = data.version
        this.fileList.push({ url: data.bannerImg })

        this.startTimeDate = s[0]
        this.startTimeShijian = s[1]
      })
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      //  console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
    },
    handleRemove() {
      this.ruleForm.bannerImg = ''
    },
    fileError(err, file, fileList) {
      // 上传出错
      this.ruleForm.bannerImg = ''
      this.$message({
        message: '上传出错',
        type: 'warning'
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.errno == 0) {
        this.ruleForm.bannerImg = res.data.url
        this.update(this.ruleForm)
      } else {
        this.$message({
          message: '上传出错',
          type: 'warning'
        })
      }
    },
    beforeAvatarUpload(file) {
      var isJPG = false
      if (
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/png' ||
        file.raw.type === 'image/gif'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      this.ruleForm.bannerImg = URL.createObjectURL(file.raw)
      this.isImgCheak = true
      return isJPG && isLt2M
    },

    onTypeChange(e) {
      // console.log(this.ruleForm.type)
    },
    handleCancel: function() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: './list' })
    },
    handlePublish() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.ruleForm.openAreaTime =
            this.startTimeDate + ' ' + this.startTimeShijian
          this.ruleForm.haveAndroid
            ? (this.ruleForm.haveAndroid = 1)
            : (this.ruleForm.haveAndroid = 0)
          this.ruleForm.haveIos
            ? (this.ruleForm.haveIos = 1)
            : (this.ruleForm.haveIos = 0)
          this.ruleForm.isRecommend
            ? (this.ruleForm.isRecommend = 1)
            : (this.ruleForm.isRecommend = 0)
          this.ruleForm.newClothes
            ? (this.ruleForm.newClothes = 1)
            : (this.ruleForm.newClothes = 0)
          this.ruleForm.newTour
            ? (this.ruleForm.newTour = 1)
            : (this.ruleForm.newTour = 0)

          if (!this.isImgCheak) {
            this.update(this.ruleForm)
          } else {
            this.$refs.uploadIMG.submit()
          }
        } else {
          this.$message({
            message: '请检查数据必填项',
            type: 'warning'
          })
          return false
        }
      })
    },

    update(e) {
      this.loading = true
      api
        .update(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.$router.push({ path: './list' })
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message({
            message: e.data,
            type: 'warning'
          })
        })
    }
  }
}
</script>
